package com.ys.web.mobao.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.ys.base.BaseParam;
import com.ys.base.EnumType;
import com.ys.utils.alipay.AliPayHandler;
import com.ys.utils.alipay.config.YsAlipayConfig;
import com.ys.utils.alipay.model.AliNotifyAppInfo;
import com.ys.utils.alipay.model.MsgInfo;
import com.ys.utils.annotation.UserPayGroupNumberCheck;
import com.ys.utils.base.http.RequestHandler;
import com.ys.utils.base.http.ResponseHandler;
import com.ys.utils.base.j2se.*;
import com.ys.utils.datasource.DynamicDataSourceContextHolder;
import com.ys.utils.http.RSAUtils;
import com.ys.utils.mobao.MobaoPay;
import com.ys.utils.mobao.Mobo360Config;
import com.ys.utils.pay.Result;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.UserKey;
import com.ys.utils.redis.key.WalletKey;
import com.ys.utils.spring.config.SystemError;
import com.ys.utils.spring.properties.Config;
import com.ys.web.ali.manager.YsAlipayConfigManager;
import com.ys.web.goods.order.model.Order;
import com.ys.web.goods.order.service.OrderService;
import com.ys.web.mobao.model.po.MobaoRechargeCreate;
import com.ys.web.mobao.model.po.Notify;
import com.ys.web.pay.PayEnum;
import com.ys.web.pay.PayService;
import com.ys.web.pay.manager.PayManager;
import com.ys.web.pay.model.PayOrder;
import com.ys.web.pay.model.po.RedPacketCreate;
import com.ys.web.pay.model.po.TransferCreate;
import com.ys.web.pay.model.vo.UserBank;
import com.ys.web.sys.notice.service.NoticeService;
import com.ys.web.sys.notice.vo.SystemNoticeVo;
import com.ys.web.user.friends.service.GroupService;
import com.ys.web.user.info.UserInfoService;
import com.ys.web.user.login.LoginInfo;
import com.ys.web.user.login.LoginService;
import com.ys.web.yinsheng.model.RequestData;
import com.ys.web.yinsheng.model.UserMerchant;
import com.ys.web.yinsheng.service.YinShengService;
import com.ys.web.yinsheng.util.ServiceEnum;
import com.ys.web.yinsheng.util.YinShengClient;
import com.ys.web.yinsheng.util.YsKJEnum;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/onlinePay/recharge/")
public class MobaoRechargeController {
    @Autowired
    private PayService payService;
    @Autowired
    private OrderService  orderService;
    @Autowired
    private YinShengService yinShengService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private YsAlipayConfigManager ysAlipayConfigManager;
    @Autowired
    private GroupService groupService;

    @Autowired
    private NoticeService noticeService;
    @RequestMapping("index")
    public String index() {
        Random random = new Random();
        int a = random.nextInt(40) + 10;
        int a2 = random.nextInt(50) + 50;
        int a3 = random.nextInt(100) + 100;
        int a4 = random.nextInt(300) + 200;
        int a5 = random.nextInt(300) + 500;
        int a6 = random.nextInt(300) + 700;

        List<String> list = new ArrayList<>();
        list.add(a+"");
        list.add(a2+"");
        list.add(a3+"");
        list.add(a4+"");
        list.add(a5+"");
        list.add(a6+"");

        return ResponseHandler.list(list);
    }

    /**
     * @作者: dhf
     * @名称:摩宝充值
     * @param uid
     * @param ip
     * @param rechargeCreate
     * @param packetCreate
     * @param transferCreate
     * @param passWord
     * @时间: 2022/9/7 20:45
     * @备注:
     * @返回值: java.lang.String
     */
    @RequestMapping("order/mb")
    public String orderMb(@RequestAttribute String uid, @RequestAttribute String ip, MobaoRechargeCreate rechargeCreate,
                        RedPacketCreate packetCreate, TransferCreate transferCreate,@RequestParam(defaultValue = "")String passWord){
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
//        String payChannel = StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys");
        //如果是红包或者转账，有限判定入参准确性
        if(rechargeCreate.getBusinessType()==2){
            packetCreate.check();
        }else if (rechargeCreate.getBusinessType()==3){
            transferCreate.check();
        }

        int dayKey = StringHandler.getInt(DateUtil.getYYMMDD());
        String key = UserKey.rechargeCreateKey(dayKey, uid);
//        String zfbMoneyAllKey = UserKey.rechargeCreateZFBMoneyAllKey(dayKey, uid);
        String moneyAllKey = UserKey.rechargeCreateMoneyAllKey(dayKey, uid);
        if(rechargeCreate.getBusinessType()==1){
            int count = StringHandler.getInt(Redis.str.get(key));
            if (count>0) {
                String setCount = Config.pp.get("wallet.recharge.money.day.num");
                if (count >= Integer.parseInt(setCount)) {
                    SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，每日最多充值" + setCount + "次");
                }
            }
//            if(rechargeCreate.getPayCode()==2){
//                String zfbMoney = Redis.str.get(zfbMoneyAllKey);
//                if(StringHandler.isNotEmpty(zfbMoney)){
//                    long zfb = StringHandler.getLong(Config.pp.get("wallet.recharge.money.zfb.all"));
//                    if(StringHandler.getLong(StringHandler.fenToLi(zfbMoney))+StringHandler.parseMoney(rechargeCreate.getAmount())>zfb){
//                        SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，支付宝每日最多充值" + StringHandler.moneyDesc(zfb) + "元");
//                    }
//                }
//            }
            String money = Redis.str.get(moneyAllKey);
            if(StringHandler.isNotEmpty(money)){
                long all = StringHandler.getLong(Config.pp.get("wallet.recharge.money.all"));
                if(StringHandler.getLong(StringHandler.fenToLi(money))+StringHandler.parseMoney(rechargeCreate.getAmount())>all){
                    SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，每日最多充值" + StringHandler.moneyDesc(all) + "元");
                }
            }
        }

        // 数据验证
        rechargeCreate.check(uid);

        UserBank userBank = null;
        if(rechargeCreate.getPayCode()==1){
            userBank = payService.getUserBankByUserIdMb(StringHandler.getLong(uid),rechargeCreate.getCardToken());
            if(StringHandler.isEmpty(userBank)){
                SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "银行卡不存在");
            }
        }
        if(StringHandler.isEmpty(rechargeCreate.getOrderId())){
            Map<String,String> order = orderService.order(uid,rechargeCreate.getAmount(),1);
            rechargeCreate.setGoodsName(order.get("goodsName"));
            rechargeCreate.setOrderId(order.get("id"));
        }

        Map<String,Object> result = new HashMap<>();
        //发起预支付
        if(rechargeCreate.getPayCode()==1){
            result = MobaoPay.payInit(userBank.getCardToken(),ip,rechargeCreate);
        }else {
            result = MobaoPay.alipay(ip,rechargeCreate);
        }
        PayOrder payOrder = new PayOrder();
        payOrder.setBusyId(uid);
        payOrder.setOrderNo(rechargeCreate.getRequestId());
        payOrder.setProductName(rechargeCreate.getGoodsName());
        payOrder.setAmount(StringHandler.getLong(rechargeCreate.getAmount()));
        payOrder.setPayType(rechargeCreate.getPayCode()==1?PayEnum.payMentType.BANK.getCode():PayEnum.payMentType.ALIPAY.getCode());
        payOrder.setPayStatus(PayEnum.PayStatus.NO_PAY.getCode());
        payOrder.setBusinessType(rechargeCreate.getBusinessType());
        payOrder.setOrderId(StringHandler.getLong(rechargeCreate.getOrderId()));
        payOrder.setPrepayNo(StringHandler.getString(result.get("prepayNo")));
        payOrder.setSerialNumber(StringHandler.getString(result.get("orderNo")));
        payOrder.setPayChannel(2);
        // 保存银行卡信息
        if(rechargeCreate.getPayCode()==1){
            assert userBank != null;
            payOrder.setMobile(userBank.getMobile());
            payOrder.setUserName(userBank.getUserName());
            payOrder.setCardNo(userBank.getCardNo());
            payOrder.setBankName(userBank.getBankName());
        }
        payService.payOrder(payOrder);
        if(rechargeCreate.getBusinessType()!=1){
            String businessTypeKey = WalletKey.orderBusinessType(rechargeCreate.getRequestId(),rechargeCreate.getBusinessType());
            Redis.str.set(businessTypeKey,JSON.toJSONString(rechargeCreate.getBusinessType()==2?packetCreate:transferCreate),1800);
        }
        if(rechargeCreate.getBusinessType()==1){
            Redis.key.increment(key);
            Redis.key.setKeyTimeout(key,86400L);
//            Redis.key.increment(zfbMoneyAllKey,payOrder.getAmount());
//            Redis.key.setKeyTimeout(zfbMoneyAllKey,86400L);
            Redis.key.increment(moneyAllKey,payOrder.getAmount());
            Redis.key.setKeyTimeout(moneyAllKey,86400L);
        }
        return ResponseHandler.success(result);
    }


    @UserPayGroupNumberCheck
    @RequestMapping("order/zfb")
    public String orderZfb(@RequestAttribute String uid, @RequestAttribute String ip, MobaoRechargeCreate rechargeCreate,
                           RedPacketCreate packetCreate, TransferCreate transferCreate,@RequestParam(defaultValue = "")String passWord){
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
        if(!rechargeCreate.whiteList(uid)) {
            if (Boolean.parseBoolean(Config.pp.get("wallet.account.ali.recharge"))) {
                SystemError.wrapBs("500", "充值功能暂时已关闭");
            }
            LoginInfo loginInfo = loginService.infoById(uid);
            if (Config.pp.get("wallet.recharge.ali.black").contains(loginInfo.getAlipayUid())) {
                SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付通道已关闭");
            }
        }
        rechargeCreate.payChannel="zfb";
        //如果是红包或者转账，有限判定入参准确性
        if(rechargeCreate.getBusinessType()==2){
            packetCreate.check();
        }
        int dayKey = StringHandler.getInt(DateUtil.getYYMMDD());
        String key = UserKey.rechargeCreateKey(dayKey, uid);
        String zfbMoneyAllKey = UserKey.rechargeCreateZFBMoneyAllKey(dayKey, uid);
        String zfbMoneyDayAllKey = UserKey.rechargeFreeDayKey(dayKey);
        String moneyAllKey = UserKey.rechargeCreateMoneyAllKey(dayKey, 0);
        String zfbAllKey = UserKey.rechargeCreateZFBMoneyAllKey(dayKey/100, 0);
        if(!rechargeCreate.whiteList(uid)) {
            if (rechargeCreate.getBusinessType() == 1) {
                int count = StringHandler.getInt(Redis.str.get(key));
                if (count > 0) {
                    String setCount = Config.pp.get("wallet.recharge.money.day.num");
                    if (count >= Integer.parseInt(setCount)) {
                        SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，每日最多充值" + setCount + "次");
                    }
                }
                String zfbMoney = Redis.str.get(zfbMoneyAllKey);
                if (StringHandler.isNotEmpty(zfbMoney)) {
                    long zfb = StringHandler.getLong(Config.pp.get("wallet.recharge.money.zfb.all"));
                    if (StringHandler.getLong(StringHandler.isEmpty(zfbMoney) ? 0 : StringHandler.fenToLi(zfbMoney)) + StringHandler.parseMoney(rechargeCreate.getAmount()) > zfb) {
                        SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，支付宝用户每日最多充值" + StringHandler.moneyDesc(zfb) + "元");
                    }
                }
                String zfbAllMoney = Redis.str.get(zfbAllKey);
                if (StringHandler.isNotEmpty(zfbAllMoney)) {
                    long zfbAll = StringHandler.getLong(Config.pp.get("wallet.recharge.money.zfb.all.money"));
                    if (StringHandler.getLong(StringHandler.isEmpty(zfbAllMoney) ? 0 : StringHandler.fenToLi(zfbAllMoney)) + StringHandler.parseMoney(rechargeCreate.getAmount()) > zfbAll) {
                        SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，支付宝每月充值已达上限，请使用银行卡充值");
                    }
                }
                //按照元计算
                String zfbDayAllMoney = Redis.str.get(zfbMoneyDayAllKey);
                if (StringHandler.isNotEmpty(zfbDayAllMoney)) {
                    long zfb = StringHandler.getLong(Config.pp.get("wallet.recharge.money.zfb.day.all"));
                    if (zfb > 0) {
                        if (StringHandler.getLong(StringHandler.isEmpty(zfbDayAllMoney) ? 0 : StringHandler.getLong(zfbDayAllMoney)) + StringHandler.getLong(rechargeCreate.getAmount()) > zfb) {
                            SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，支付宝每日已达上限");
                        }
                    }
                }
                String money = Redis.str.get(moneyAllKey);
                if(StringHandler.isNotEmpty(money)){
                    long all = StringHandler.getLong(Config.pp.get("wallet.recharge.money.all"));
                    if(StringHandler.getLong(StringHandler.fenToLi(money))+StringHandler.parseMoney(rechargeCreate.getAmount())>all){
    //                    SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，每日最多充值" + StringHandler.moneyDesc(all) + "元");
                        SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，支付宝每日充值已达上限，请使用银行卡充值");
                    }
                }
                //判断人员是否只能用银行卡
                if(Boolean.parseBoolean(Config.pp.get("ys.bank.group.user.check.open"))){
                    String str = Config.pp.get("ys.bank.group.list");
                    if(StringHandler.isNotEmpty(str)){
                        List<String> group = Arrays.asList(str.split(","));
                        if(StringHandler.isNotEmpty(group) && group.size()>0) {
                            List<Long> userGroupIdList = groupService.userGroupId(uid);
                            group.stream().forEach(groupId -> {
                                if (userGroupIdList.contains(StringHandler.getLong(groupId))) {
                                    SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "请使用银行卡充值");
                                }
                            });
                        }
//                        if(StringHandler.isNotEmpty(userGroupIdList)){
//                            for (String groupId:group) {
//                                for (long userGroupId:userGroupIdList) {
//                                    if(StringHandler.getLong(groupId)==userGroupId){
//                                        SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "请使用银行卡充值");
//                                    }
//                                }
//                            }
//                        }
                    }
                }
            }

        }

        // 数据验证
        rechargeCreate.check(uid);

        UserBank userBank = null;
        if(rechargeCreate.getPayCode()==1){
            userBank = payService.getUserBankByUserIdMb(StringHandler.getLong(uid),rechargeCreate.getCardToken());
            if(StringHandler.isEmpty(userBank)){
                SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "银行卡不存在");
            }
        }
        if(StringHandler.isEmpty(rechargeCreate.getOrderId())){
            Map<String,String> order = orderService.order(uid,rechargeCreate.getAmount(),3);
            rechargeCreate.setGoodsName(order.get("goodsName"));
            rechargeCreate.setOrderId(order.get("id"));
        }

        Map<String,Object> result = new HashMap<>();
        try {
            MsgInfo msgInfo = null;
            String appid = "";

            if(!Boolean.parseBoolean(Config.pp.get("ys.ali.pay.appid.all.open"))){
                AliPayHandler aliPayHandler = null;
                if(Logger.isOnline()){
                    YsAlipayConfig ysAlipayConfig = ysAlipayConfigManager.getAppId();
                    aliPayHandler = new AliPayHandler(ysAlipayConfig);
                    appid = ysAlipayConfig.appId;
                }else{
                    aliPayHandler = new AliPayHandler("test");
                    appid = "2021003187690103";
                }
                JSONObject bizContent = aliPayHandler.bizContent(rechargeCreate.getRequestId(),StringHandler.fenToYuan(rechargeCreate.getAmount()),
                        "商品","用户ID--"+uid,"app","");
                msgInfo = aliPayHandler.appPay(appid,bizContent, Mobo360Config._notifyUrl+"/onlinePay/recharge/notify/zfb");
            }else{
                AliPayHandler aliPayHandler = null;
                if(Logger.isOnline()){
                    YsAlipayConfig ysAlipayConfig = ysAlipayConfigManager.getAppId();
                    if(StringHandler.isEmpty(ysAlipayConfig)){
                        log.error("支付失败----------ysAlipayConfig--------为空");
                        SystemError.wrapBs("500", "支付失败");
                    }
                    appid = ysAlipayConfig.appId;
                    if(StringHandler.isEmpty(appid)){
                        log.error("支付失败----------appid--------为空");
                        SystemError.wrapBs("500", "支付失败");
                    }
                    aliPayHandler = new AliPayHandler(ysAlipayConfig);
                }else{
                    aliPayHandler = new AliPayHandler("test");
                    appid = "2021003187690103";
                }
                JSONObject bizContent = aliPayHandler.bizContent(rechargeCreate.getRequestId(),StringHandler.fenToYuan(rechargeCreate.getAmount()),
                        "商品","用户ID--"+uid,"app","");
//                msgInfo = AliPayHandlerV2.appPay(defaultAlipayClient, bizContent,Mobo360Config._notifyUrl+"/onlinePay/recharge/notify/zfb");

                msgInfo = aliPayHandler.appPay(appid,bizContent, Mobo360Config._notifyUrl+"/onlinePay/recharge/notify/zfb");
            }
            if(msgInfo.isSuccess){
                result.put("aliCode",msgInfo.msg);
                PayOrder payOrder = new PayOrder();
                payOrder.setBusyId(uid);
                payOrder.setOrderNo(rechargeCreate.getRequestId());
                payOrder.setProductName(rechargeCreate.getGoodsName());
                payOrder.setAmount(StringHandler.getLong(rechargeCreate.getAmount()));
                payOrder.setPayType("4");
                payOrder.setPayStatus(PayEnum.PayStatus.NO_PAY.getCode());
                payOrder.setBusinessType(rechargeCreate.getBusinessType());
                payOrder.setOrderId(StringHandler.getLong(rechargeCreate.getOrderId()));
                payOrder.setPrepayNo(StringHandler.getString(result.get("prepayNo")));
                payOrder.setSerialNumber(StringHandler.getString(result.get("orderNo")));
                payOrder.setPayChannel(3);
                payOrder.setAppid(appid);
                // 保存银行卡信息
                if(rechargeCreate.getPayCode()==1){
                    assert userBank != null;
                    payOrder.setMobile(userBank.getMobile());
                    payOrder.setUserName(userBank.getUserName());
                    payOrder.setCardNo(userBank.getCardNo());
                    payOrder.setBankName(userBank.getBankName());
                }
                payService.payOrder(payOrder);
                if(rechargeCreate.getBusinessType()!=1){
                    String businessTypeKey = WalletKey.orderBusinessType(rechargeCreate.getRequestId(),rechargeCreate.getBusinessType());
                    Redis.str.set(businessTypeKey,JSON.toJSONString(rechargeCreate.getBusinessType()==2?packetCreate:transferCreate),1800);
                }
                if(rechargeCreate.getBusinessType()==1){
                    Redis.key.increment(key);
                    Redis.key.setKeyTimeout(key,86400L);
                    Redis.key.increment(zfbMoneyAllKey,payOrder.getAmount());
                    Redis.key.setKeyTimeout(zfbMoneyAllKey,86400L);
                    Redis.key.increment(zfbAllKey,payOrder.getAmount());
                    Redis.key.setKeyTimeout(zfbAllKey,86400L);
                    Redis.key.increment(moneyAllKey,payOrder.getAmount());
                    Redis.key.setKeyTimeout(moneyAllKey,86400L);
                    Redis.key.increment(zfbMoneyDayAllKey,StringHandler.getLong(rechargeCreate.getAmount())/100);
                    Redis.key.setKeyTimeout(zfbMoneyDayAllKey,24*60*60L);
                }
            }
        } catch (AlipayApiException e) {
            log.error("支付失败------------------",e);
            SystemError.wrapBs("500", "支付失败");
        }
        return ResponseHandler.success(result);
    }
    /**
     * 支付预下单
     * @param uid
     * @param ip
     * @param rechargeCreate
     * @param packetCreate
     * @param transferCreate
     * @return
     */
    @RequestMapping("order")
    public String order(@RequestAttribute String uid, @RequestAttribute String ip, MobaoRechargeCreate rechargeCreate,
                        RedPacketCreate packetCreate, TransferCreate transferCreate,@RequestParam(defaultValue = "")String passWord){
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
        if(Logger.isOnline()) {
            if (Boolean.parseBoolean(Config.pp.get("trading.disable.ys.reg"))) {
                SystemError.wrapBs("500", "银行卡充值已关闭");
            }
        }
        String payChannel = StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys");
        if(StringHandler.getInt(Config.pp.get("ys.pay.password.switch"))==1 || "mb".equals(payChannel)){
            if (StringHandler.isEmpty(passWord)) {
                return ResponseHandler.error("500", "请输入密码");
            }
            LoginInfo userVo = loginService.infoByUid(StringHandler.getString(uid));
            if (!PayManager.validatePayPassword(RSAUtils.decryptField(passWord), userVo)) {
                SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
            }
        }
        //如果是红包或者转账，有限判定入参准确性
        if(rechargeCreate.getBusinessType()==2){
            packetCreate.check();
        }else if (rechargeCreate.getBusinessType()==3){
            transferCreate.check();
        }

        int dayKey = StringHandler.getInt(DateUtil.getYYMMDD());
        String key = UserKey.rechargeCreateKey(dayKey, uid);
//        String zfbMoneyAllKey = UserKey.rechargeCreateZFBMoneyAllKey(dayKey, uid);
        String moneyAllKey = UserKey.rechargeCreateMoneyAllKey(dayKey, uid);
        if(rechargeCreate.getBusinessType()==1){
            int count = StringHandler.getInt(Redis.str.get(key));
            if (count>0) {
                String setCount = Config.pp.get("wallet.recharge.money.day.num");
                if (count >= Integer.parseInt(setCount)) {
                    SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，每日最多充值" + setCount + "次");
                }
            }
//            if(rechargeCreate.getPayCode()==2){
//                String zfbMoney = Redis.str.get(zfbMoneyAllKey);
//                if(StringHandler.isNotEmpty(zfbMoney)){
//                    long zfb = StringHandler.getLong(Config.pp.get("wallet.recharge.money.zfb.all"));
//                    if(StringHandler.getLong(StringHandler.fenToLi(zfbMoney))+StringHandler.parseMoney(rechargeCreate.getAmount())>zfb){
//                        SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，支付宝每日最多充值" + StringHandler.moneyDesc(zfb) + "元");
//                    }
//                }
//            }
            String money = Redis.str.get(moneyAllKey);
            if(StringHandler.isNotEmpty(money)){
                long all = StringHandler.getLong(Config.pp.get("wallet.recharge.money.all"));
                if(StringHandler.getLong(StringHandler.fenToLi(money))+StringHandler.parseMoney(rechargeCreate.getAmount())>all){
                    SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "充值失败，每日最多充值" + StringHandler.moneyDesc(all) + "元");
                }
            }
        }

        // 数据验证
        rechargeCreate.check(uid);

        UserBank userBank = null;
        if(rechargeCreate.getPayCode()==1){
            userBank = payService.getUserBankByUserId(StringHandler.getLong(uid),rechargeCreate.getCardToken());
            if(StringHandler.isEmpty(userBank)){
                SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "银行卡不存在");
            }
        }
//        if(StringHandler.isEmpty(rechargeCreate.getOrderId())){
//            Map<String,String> order = orderService.order(uid,rechargeCreate.getAmount(),1);
//            rechargeCreate.setGoodsName(order.get("goodsName"));
//            rechargeCreate.setOrderId(order.get("id"));
//        }

        Map<String,Object> result = new HashMap<>();
        /**支付渠道  mb 摩宝 ys 银盛  sxy 首信易 um U盟 */
        if("ys".equals(payChannel)){
            UserMerchant userMerchant = yinShengService.userMerchant(uid);
            if(StringHandler.isEmpty(userMerchant)){
                SystemError.wrapBs("500","该用户实名认证信息有误");
            }
            // 组装业务参数
            Map<String,Object> requestMap = new HashMap<>();
            requestMap.put("requestNo",rechargeCreate.getRequestId());
            requestMap.put("merchantNo",userMerchant.merchantNo);//银盛商户号
            requestMap.put("amount",StringHandler.fenToYuan(rechargeCreate.amount));//充值金额，单位：元 取值范围：0.01-999999.99
            if(StringHandler.getInt(Config.pp.get("ys.pay.test.open"),0)==1){
                String testUser = StringHandler.getString(Config.pp.get("ys.pay.test.user"),"");
                if(StringHandler.isNotEmpty(testUser)){
                    List<String> testUserList = Arrays.asList(testUser.split(","));
                    if(testUserList.contains(uid)){
                        requestMap.put("amount","0.01");
                    }
                }
            }
            requestMap.put("linkId",userBank.getLinkId());//绑卡标识，绑卡成功后系统返回的唯一标识
            requestMap.put("remark","用户充值uid："+uid);//订单备注，无实际作用，仅记录
            requestMap.put("notifyUrl","https://interface.ys168.vip/ys/callBack/recharge/notify");//充值结果异步通知地址，为空则不通知
            RequestData requestData = new RequestData(requestMap);
            YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_RECHARGE);
            Map<String, Object> map = yinShengClient.requestApi(requestData,"用户充值");
            if(StringHandler.isEmpty(map)){
                SystemError.wrapBs("500","用户充值失败");
            }
            String authSn = StringHandler.getString(map.get("authSn"));
            result.put("authSn",authSn);
            result.put("requestNo",rechargeCreate.getRequestId());
        }else{
            //发起预支付
            if(rechargeCreate.getPayCode()==1){
                result = MobaoPay.payInit(userBank.getCardToken(),ip,rechargeCreate);
            }else {
                result = MobaoPay.alipay(ip,rechargeCreate);
            }
        }
        PayOrder payOrder = new PayOrder();
        payOrder.setBusyId(uid);
        payOrder.setOrderNo(rechargeCreate.getRequestId());
        payOrder.setProductName(rechargeCreate.getGoodsName());
        payOrder.setAmount(StringHandler.getLong(rechargeCreate.getAmount()));
        payOrder.setPayType(rechargeCreate.getPayCode()==1?PayEnum.payMentType.BANK.getCode():PayEnum.payMentType.ALIPAY.getCode());
        payOrder.setPayStatus(PayEnum.PayStatus.NO_PAY.getCode());
        payOrder.setBusinessType(rechargeCreate.getBusinessType());
        payOrder.setOrderId(StringHandler.getLong(rechargeCreate.getOrderId()));
        payOrder.setPrepayNo(StringHandler.getString(result.get("prepayNo")));
        payOrder.setSerialNumber(StringHandler.getString(result.get("orderNo")));
        payOrder.setPayChannel(1);
        // 保存银行卡信息
        if(rechargeCreate.getPayCode()==1){
            assert userBank != null;
            payOrder.setMobile(userBank.getMobile());
            payOrder.setUserName(userBank.getUserName());
            payOrder.setCardNo(userBank.getCardNo());
            payOrder.setBankName(userBank.getBankName());
        }
        payService.payOrder(payOrder);
        if(rechargeCreate.getBusinessType()!=1){
            String businessTypeKey = WalletKey.orderBusinessType(rechargeCreate.getRequestId(),rechargeCreate.getBusinessType());
            Redis.str.set(businessTypeKey,JSON.toJSONString(rechargeCreate.getBusinessType()==2?packetCreate:transferCreate),1800);
        }
        if(rechargeCreate.getBusinessType()==1){
            Redis.key.increment(key);
            Redis.key.setKeyTimeout(key,86400L);
//            Redis.key.increment(zfbMoneyAllKey,payOrder.getAmount());
//            Redis.key.setKeyTimeout(zfbMoneyAllKey,86400L);
            Redis.key.increment(moneyAllKey,payOrder.getAmount());
            Redis.key.setKeyTimeout(moneyAllKey,86400L);
        }
        return ResponseHandler.success(result);
    }

    /**
     * @作者: dhf
     * @名称:摩宝商品购买
     * @param uid
     * @param ip
     * @param orderId
     * @param cardToken
     * @param passWord
     * @时间: 2022/9/7 20:45
     * @备注:
     * @返回值: java.lang.String
     */
    @RequestMapping("order/pay/mb")
    public String orderPayMb(@RequestAttribute String uid, @RequestAttribute String ip,long orderId,String cardToken,@RequestParam(defaultValue = "")String passWord) {
        if (StringHandler.getInt(Config.pp.get("ys.goods.pay.switch"),1)==0) {
            return ResponseHandler.error("500", "该功能研发中...");
        }
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
        String payChannel = StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys");
        if(StringHandler.isEmpty(orderId)){
            SystemError.wrapBs("500", "订单信息错误");
        }
        Map<String,Object> goods = orderService.goodsOrderInfo(orderId,0);
        if(StringHandler.isEmpty(goods)) {
            SystemError.wrapBs("500", "订单信息错误");
        }
        if (StringHandler.isEmpty(passWord)) {
            return ResponseHandler.error("500", "请输入密码");
        }
        LoginInfo userVo = loginService.infoByUid(StringHandler.getString(uid));
        if (!PayManager.validatePayPassword(RSAUtils.decryptField(passWord), userVo)) {
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
        }
        if(payChannel.equals("mb")){
            int i = orderService.goodsOrderUpdate(orderId, StringHandler.getString(Config.pp.get("ys.merchant.mb.id"), "199950003582"),-1);
            if (i < 0) {
                SystemError.wrapBs("500", "该订单已支付，不需要重复支付");
            }
            // 修改用户账户金额
            Result<?> result1 = PayManager.accountModify(StringHandler.getLong(goods.get("uid")), PayEnum.AccountFlowType.PAY_ORDER,
                    StringHandler.yuanToFen(goods.get("order_amount")+""),"商品购买支付",1);
            // 支付失败
            if(!result1.success()){
                Logger.error("商品购买支付失败："+JSON.toJSONString(goods));
                orderService.orderPayStatus(StringHandler.getString(goods.get("order_sn")), 10, DateUtil.getDatetimeLong(), "", "");
                SystemError.wrapBs("500", "商品购买支付失败");
            }else{
                orderService.orderPayStatus(StringHandler.getString(goods.get("order_sn")), 1, DateUtil.getDatetimeLong(), "", BaseParam.busNo("PAY"));
            }

        }
        return ResponseHandler.success();
    }
    @RequestMapping("order/pay/zfb")
    public String orderPayZfb(@RequestAttribute String uid, @RequestAttribute String ip,long orderId,@RequestParam(defaultValue = "")String passWord) {
        if (StringHandler.getInt(Config.pp.get("ys.goods.pay.switch"),1)==0) {
            return ResponseHandler.error("500", "该功能研发中...");
        }
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
//        int bankCount = payService.getUserBankByUserIdCount(StringHandler.getLong(uid));
//        if(bankCount<=0){
//            SystemError.wrapBs("500","该用户实名绑卡后购买");
//        }
        Map<String,Object> goods = orderService.goodsOrderInfo(orderId,0);
        if(StringHandler.isEmpty(goods)) {
            SystemError.wrapBs("500", "订单信息错误");
        }
        if (StringHandler.isEmpty(passWord)) {
            return ResponseHandler.error("500", "请输入密码");
        }
        LoginInfo userVo = loginService.infoByUid(StringHandler.getString(uid));
        if (!PayManager.validatePayPassword(RSAUtils.decryptField(passWord), userVo)) {
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
        }
        int i = orderService.goodsOrderUpdate(orderId, StringHandler.getString(Config.pp.get("ys.merchant.mb.id"), "199950003582"),-1);
        if (i < 0) {
            SystemError.wrapBs("500", "该订单已支付，不需要重复支付");
        }
        long order_amount = StringHandler.yuanToFen(goods.get("order_amount")+"");
        int source = StringHandler.getInt(goods.get("source"));
        if(source==2) {
            order_amount = StringHandler.getLong(goods.get("order_amount"));
        }
        // 修改用户账户金额
        Result<?> result1 = PayManager.accountModifyZfb(StringHandler.getLong(goods.get("uid")), PayEnum.AccountFlowType.PAY_ORDER,
                order_amount,"商品购买支付");
        // 支付失败
        if(!result1.success()){
            Logger.error("商品购买支付失败："+JSON.toJSONString(goods));
            orderService.orderPayStatus(StringHandler.getString(goods.get("order_sn")), 10, DateUtil.getDatetimeLong(), "", "");
            SystemError.wrapBs("500", result1.getMessage());
        }else{
            orderService.orderPayStatus(StringHandler.getString(goods.get("order_sn")), 1, DateUtil.getDatetimeLong(), "", BaseParam.busNo("PAY"));
            //给在线客服发送通知
            noticeService.sendOverdueBackNotice(SystemNoticeVo
                    .build("商品购买通知",String.format("<p>你有一笔商品购买订单</p>" +
                                            "<p>用户id：%s</p>" +
                                            "<p>支付金额：%s元</p>" +
                                            "<p>支付时间：%s</p>" +
                                            "<p>订单编号：%s</p>",
                                    uid,
                                    goods.get("order_amount"),
                                    DateUtil.getDate(),
                                    goods.get("order_sn")),
                            0));
            if(StringHandler.getInt(goods.get("source"))==2){
                Map<String, Object> params = new HashMap<>();
                params.put("orderId",orderId+"");
//                HttpUtils.post("http://127.0.0.1:8881/jst/order/notice/api",params);
                //异步请求，通知商品项目不影响返回前端数据
                OkHttpUtils.postAsync("http://127.0.0.1:8881/jst/order/notice/api", params, (Response response) -> {
                    String reJson = "null";
                    try {
                        reJson = response.body().string();
                        JSONObject jsonObject = JSON.parseObject(reJson);
                        if(!jsonObject.getInteger("code").equals(0)){
                            log.error("异步通知商品项目失败", reJson);
                        }else{
                            log.info("异步通知商品项目成功", reJson);
                        }
                    } catch (IOException e) {
                        log.error("异步通知商品项目异常", reJson);
                        e.printStackTrace();
                    }
                });
            }
        }

        return ResponseHandler.success();
    }

    @RequestMapping("order/goods/pay/zfb")
    public String orderGoodsPayZfb(@RequestAttribute String uid,long orderId,@RequestParam(defaultValue = "")String passWord) {
        if (StringHandler.getInt(Config.pp.get("ys.goods.pay.switch"),1)==0) {
            return ResponseHandler.error("500", "该功能研发中...");
        }
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
        Map<String,Object> goods = orderService.goodsOrderInfo(orderId,0);
        if(StringHandler.isEmpty(goods)) {
            SystemError.wrapBs("500", "订单信息错误");
        }
        if (StringHandler.isEmpty(passWord)) {
            return ResponseHandler.error("500", "请输入密码");
        }
        LoginInfo userVo = loginService.infoByUid(StringHandler.getString(uid));
        if (!PayManager.validatePayPassword(RSAUtils.decryptField(passWord), userVo)) {
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
        }
        int i = orderService.goodsOrderUpdate(orderId, StringHandler.getString(Config.pp.get("ys.merchant.mb.id"), "199950003582"),-1);
        if (i < 0) {
            SystemError.wrapBs("500", "该订单已支付，不需要重复支付");
        }
        AliPayHandler aliPayHandler = new AliPayHandler(Config.pp);
        // 发起支付宝支付
        JSONObject bizContent = aliPayHandler.bizContent(StringHandler.getString(goods.get("order_sn")),StringHandler.getString(goods.get("order_amount")),
                "商品购买",StringHandler.getString(goods.get("goods_name")),"app","");
        List<String> obj = JSONObject.parseArray(Config.pp.get("ys.apipay.appid"),String.class);
        MsgInfo msgInfo = null;
        try {
            msgInfo = aliPayHandler.appPay(obj.get(0),bizContent, Mobo360Config._notifyUrl+"/onlinePay/recharge/goods/notify/zfb");
        } catch (AlipayApiException e) {
            SystemError.wrapBs("600","支付失败");
        }
        if(!msgInfo.isSuccess){
        // 支付失败
            Logger.error("商品购买支付失败："+JSON.toJSONString(goods));
            orderService.orderPayStatus(StringHandler.getString(goods.get("order_sn")), 10, DateUtil.getDatetimeLong(), "", "");
            SystemError.wrapBs("500", msgInfo.errMsg);
        }
        return ResponseHandler.success(msgInfo.msg);
    }
    /**
     * @作者: dhf
     * @名称:银盛商品购买
     * @param uid
     * @param ip
     * @param orderId
     * @param cardToken
     * @param passWord
     * @时间: 2022/9/7 20:46
     * @备注:
     * @返回值: java.lang.String
     */
    @RequestMapping("order/pay")
    public String orderPay(@RequestAttribute String uid, @RequestAttribute String ip,long orderId,String cardToken,@RequestParam(defaultValue = "")String passWord) {
        if (StringHandler.getInt(Config.pp.get("ys.goods.pay.switch"),1)==0) {
            return ResponseHandler.error("500", "该功能研发中...");
        }
        if (Boolean.parseBoolean(Config.pp.get("wallet.recharge.switch"))) {
            return ResponseHandler.error("500", "系统维护");
        }
        String payChannel = StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys");
        if(StringHandler.getInt(Config.pp.get("ys.pay.password.switch"))==1 || "mb".equals(payChannel)){
            if (StringHandler.isEmpty(passWord)) {
                return ResponseHandler.error("500", "请输入密码");
            }
            LoginInfo userVo = loginService.infoByUid(StringHandler.getString(uid));
            if (!PayManager.validatePayPassword(RSAUtils.decryptField(passWord), userVo)) {
                SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
            }
        }

        if(StringHandler.isEmpty(orderId)){
            SystemError.wrapBs("500", "订单信息错误");
        }
        Map<String,Object> goods = orderService.goodsOrderInfo(orderId,0);
        if(StringHandler.isEmpty(goods)) {
            SystemError.wrapBs("500", "订单信息错误");
        }
        if(payChannel.equals("ys")) {
            //支付
            UserMerchant userMerchant = yinShengService.userMerchant(uid);
            if (StringHandler.isEmpty(userMerchant)) {
                SystemError.wrapBs("500", "该用户实名认证信息有误");
            }
            UserBank userBank = payService.getUserBankByUserId(StringHandler.getLong(uid), cardToken);
            if (StringHandler.isEmpty(userBank)) {
                SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "银行卡不存在");
            }
            //收取账户
//        Map<String,Object> collectionUser = yinShengService.collectionUser();
//        long collectionUid = 47144;
//        String payeeMerchantNo = "Y151119861025195";
//        if(StringHandler.isNotEmpty(collectionUser)) {
//            payeeMerchantNo = StringHandler.getString(collectionUser.get("merchantNo"));
//            collectionUid = StringHandler.getLong(collectionUser.get("uid"));
//        }
            Map<String, Object> result = new HashMap<>();
            // 组装业务参数
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("requestNo", goods.get("order_sn"));
            requestMap.put("payeeMerchantNo", StringHandler.getString(Config.pp.get("ys.merchant.id"), "826691148160089"));//收款方银盛商户号
            requestMap.put("payerMerchantNo", userMerchant.merchantNo);//付款方银盛商户号
            requestMap.put("amount", goods.get("order_amount"));//充值金额，单位：元 取值范围：0.01-999999.99
            if (StringHandler.getInt(Config.pp.get("ys.pay.test.open"), 0) == 1) {
                String testUser = StringHandler.getString(Config.pp.get("ys.pay.test.user"), "");
                if (StringHandler.isNotEmpty(testUser)) {
                    List<String> testUserList = Arrays.asList(testUser.split(","));
                    if (testUserList.contains(uid)) {
                        requestMap.put("amount", "0.01");
                    }
                }
            }
//        requestMap.put("orderDesc",goods.get("goods_name"));//
            requestMap.put("orderDesc", "蜂省优选订单支付,id：" + goods.get("id"));//
            requestMap.put("accountType", StringHandler.getInt(goods.get("type")) == 1 ? "BANKACCOUNT" : "BALANCE");
            requestMap.put("linkId", userBank.getLinkId());//绑卡标识，绑卡成功后系统返回的唯一标识
            requestMap.put("remark", "支付购买uid：" + uid);//订单备注，无实际作用，仅记录
            requestMap.put("notifyUrl", "https://interface.ys168.vip/ys/callBack/consume/notify");//充值结果异步通知地址，为空则不通知
            RequestData requestData = new RequestData(requestMap);
            YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_CONSUME);
            int i = orderService.goodsOrderUpdate(orderId, StringHandler.getString(Config.pp.get("ys.merchant.id"), "826691148160089"),-1);
            if (i < 0) {
                SystemError.wrapBs("500", "该订单已支付，不需要重复支付");
            }
            String remark = "";
            String authSn = "";
            String callback = yinShengClient.requestStrApi(requestData);
            Map<String, Object> obj = JsonUtil.jsonToBean(callback, Map.class);
            String code = StringHandler.getString(obj.get("code"), "");
            if (!code.equals(YsKJEnum.TRUSTEESHIPSTATUS.银盛响应成功.getCode())) {
                orderService.orderPayStatus(StringHandler.getString(goods.get("order_sn")), 10, DateUtil.getDatetimeLong(), "", "");
                log.error("银盛渠道支付返回错误:" + obj.get("msg"));
//			SystemError.wrapBs("500",msg+"错误");
                SystemError.wrapBs("500", obj.get("msg") + "");
            }
            if (StringHandler.isEmpty(obj.get("bizResponseJson"))) {
                orderService.orderPayStatus(StringHandler.getString(goods.get("order_sn")), 10, DateUtil.getDatetimeLong(), "", "");
                log.error("银盛渠道返支付回错误:bizResponseJson为空");
                SystemError.wrapBs("500", "支付错误");
            }
            if (StringHandler.isNotEmpty(StringHandler.getString(obj.get("bizResponseJson")))) {
                Map<String, Object> bizResponseJson = JsonUtil.jsonNullToBean(JsonUtil.toJson(obj.get("bizResponseJson")), Map.class);
                String subMsg = StringHandler.getString(bizResponseJson.get("subMsg"));
                if (bizResponseJson.get("subCode").equals(YsKJEnum.TRUSTEESHIPSTATUS.银盛业务响应成功.getCode())) {
                    authSn = StringHandler.getString(bizResponseJson.get("authSn"));
                } else if (bizResponseJson.get("subCode").equals(YsKJEnum.TRUSTEESHIPSTATUS.银盛业务响应处理中.getCode()) && subMsg.contains("处理中")) {
                    authSn = StringHandler.getString(bizResponseJson.get("authSn"));
                } else {
                    orderService.orderPayStatus(StringHandler.getString(goods.get("order_sn")), 10, DateUtil.getDatetimeLong(), "", "");
                    remark = "支付失败:" + StringHandler.getString(bizResponseJson.get("subMsg"));
                    log.error(remark);
                    SystemError.wrapBs("500", remark);
                }
            } else {
                orderService.orderPayStatus(StringHandler.getString(goods.get("order_sn")), 10, DateUtil.getDatetimeLong(), "", "");
                remark = "支付失败:返回信息为空";
                log.error(remark);
                SystemError.wrapBs("500", remark);
            }
            result.put("authSn", authSn);
            result.put("requestNo", goods.get("order_sn"));
//        if(ii==1){
//            //手续费账户，收取提现手续费
//            PayManager.accountModify(collectionUid, PayEnum.AccountFlowType.PAY_ORDER_MONEY, StringHandler.parseMoney(requestMap.get("amount")+""), "订单支付收款");
//        }
            return ResponseHandler.success(result);
        }
        return ResponseHandler.success();
    }
    /**
     * 支付确认
     * @param orderNo 预下单返回的
     * @param code    短信验证码
     * @param smsId   预下单 返回的
     * @return 00 成功 01 待支付 02 失败 08 关闭 09 处理中
     */
    @RequestMapping("payment")
    public String payment(String orderNo,String code,String smsId){
        String status;
        status = MobaoPay.payment(orderNo, code, smsId);
        if(status.equals("00")){
            PayOrder payOrder = payService.payOrderBySerialNumber(orderNo);
            // 修改支付状态
            payOrder.setPayStatus(PayEnum.PayStatus.PAID.getCode());
            payOrder.setDayKey(DateUtil.getYYMMDD());
            // 异步修改商品订单信息
            if(payOrder.getBusinessType()==4){
                orderService.orderStatus(StringHandler.getString(payOrder.getOrderId()));
            }else {
                // 修改用户账户金额
                Result<?> result1 = PayManager.accountModify(StringHandler.getLong(payOrder.getBusyId()), PayEnum.AccountFlowType.TYPE_RECHARGE,
                        payOrder.getAmount(),
                        payOrder.getPayType().equals(PayEnum.payMentType.BANK.getCode())?String.format("余额充值-来自%s(%s)",payOrder.getBankName(),payOrder.getCardNo().substring(payOrder.getCardNo().length()-4)):"余额充值-来自支付宝",1);
                // 支付失败
                if(!result1.success()){
                    Logger.error("充值修改账户金额失败："+JSON.toJSONString(payOrder));
                }
            }
        }
        return ResponseHandler.success(status);
    }

    /**
     * 接收充值状态的回调
     *
     * @return
     */
    @RequestMapping("send")
    public String send(@RequestBody Notify notify) {
        PayOrder payOrder = payService.payOrderByNo(notify.getMerchTradeNo());
        if(!payOrder.getPayStatus().equals(PayEnum.PayStatus.NO_PAY.getCode())){
            return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
        }
        // 修改支付状态
        payOrder.setPayStatus(notify.getOrderStatus().equals("00")?PayEnum.PayStatus.PAID.getCode():PayEnum.PayStatus.FAIL.getCode());
        payOrder.setDayKey(notify.getNotifyTime().substring(0,8));
        int i = payService.payOrderStatusChange(payOrder);
        if(i!=1){
            return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
        }
        if(!notify.getOrderStatus().equals("00")){
            //次数-1
            if(payOrder.getBusinessType()==1){
                String key = UserKey.rechargeCreateKey(payOrder.getDayKey(), payOrder.getBusyId());
                String zfbMoneyAllKey = UserKey.rechargeCreateZFBMoneyAllKey(payOrder.getDayKey(), payOrder.getBusyId());
                String moneyAllKey = UserKey.rechargeCreateMoneyAllKey(payOrder.getDayKey(), payOrder.getBusyId());
                Redis.key.increment(key, -1);
                Redis.str.incr(zfbMoneyAllKey, -payOrder.getAmount());
                Redis.str.incr(moneyAllKey, -payOrder.getAmount());
            }
        }else{
            // 异步修改商品订单信息
            if(payOrder.getBusinessType()==4){
                JSONObject merchParam = JSONObject.parseObject(notify.getMerchParam());
                orderService.orderStatus(merchParam.getString("orderId"));
            }else {
                // 修改用户账户金额
                Result<?> result1 = PayManager.accountModify(StringHandler.getLong(payOrder.getBusyId()), PayEnum.AccountFlowType.TYPE_RECHARGE,
                        payOrder.getAmount(),
                        payOrder.getPayType().equals(PayEnum.payMentType.BANK.getCode())?String.format("余额充值-来自%s(%s)",payOrder.getBankName(),payOrder.getCardNo().substring(payOrder.getCardNo().length()-4)):"余额充值-来自支付宝",1);
                // 支付失败
                if(!result1.success()){
                    Logger.error("充值修改账户金额失败："+JSON.toJSONString(payOrder));
                }
            }
        }
        return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
    }

    @RequestMapping("/notify/zfb")
    public String notifyZfb(AliNotifyAppInfo notifyInfo) {
        if(StringHandler.isEmpty(notifyInfo.out_trade_no)){
            log.error("支付返回订单编号为空: {}", notifyInfo, new RuntimeException());
            return "fail";
        }
        PayOrder payOrder = payService.payOrderByNo(notifyInfo.getOut_trade_no());
        if(!payOrder.getPayStatus().equals(PayEnum.PayStatus.NO_PAY.getCode())){
            return "success";
        }
        if(payOrder.getPayStatus().equals(PayEnum.PayStatus.PAID.getCode())){
            return "success";
        }

        //删除优惠券信息
        try {
            MsgInfo msgInfo = null;
            String alipayPublicCertPath = "";
            AliPayHandler aliPayHandler = null;
            if(Logger.isOnline()){
                YsAlipayConfig ysAlipayConfig = ysAlipayConfigManager.ysAlipayConfig(notifyInfo.app_id);
                alipayPublicCertPath = ysAlipayConfig.aliCpkCrt;
                aliPayHandler = new AliPayHandler(ysAlipayConfig);
            }else{
                aliPayHandler = new AliPayHandler("test");
                alipayPublicCertPath = "D:\\\\alipayCertPublicKey_RSA2.crt";
            }
            msgInfo = aliPayHandler.appNotify(notifyInfo,alipayPublicCertPath);

            log.info("notifyZfb--------------------"+Json.toJson(msgInfo));
            if(msgInfo.isSuccess){
                // 修改支付状态
                payOrder.setPayStatus(PayEnum.PayStatus.PAID.getCode());
                payOrder.setSerialNumber(notifyInfo.trade_no);
                payOrder.setCardNo(notifyInfo.buyer_id);
                payOrder.setDayKey(StringHandler.getString(DateHandler.getLongFormatDate(notifyInfo.gmt_payment)/1000000));
                int i = payService.payOrderStatusZfb(payOrder);
                if(i!=1){
                    return "success";
                }
                // 修改用户账户金额
                Result<?> result1 = PayManager.accountModifyZfb(StringHandler.getLong(payOrder.getBusyId()), PayEnum.AccountFlowType.TYPE_RECHARGE,
                        payOrder.getAmount(),
                        payOrder.getPayType().equals(PayEnum.payMentType.BANK.getCode())?String.format("余额充值-来自%s(%s)",payOrder.getBankName(),payOrder.getCardNo().substring(payOrder.getCardNo().length()-4)):"余额充值-来自支付宝");
                // 支付失败
                if(!result1.success()){
                    Logger.error("充值修改账户金额失败："+JSON.toJSONString(payOrder));
                }
                try {
                    LoginInfo longInfo = loginService.infoByUid(payOrder.getBusyId());
                    //用户充值支付宝账号和绑定账号不一致，冻结用户
                    if(!notifyInfo.buyer_id.equals(longInfo.alipayUid)){
                        // 添加拉黑
                        userInfoService.userWithdrawBlackInsert(StringHandler.getLong(payOrder.getBusyId()),DateHandler.getLongFormatDate());
                        // 修改提现记录状态
                        userInfoService.withdrawRecordStatus(StringHandler.getLong(payOrder.getBusyId()),7);
                        log.info("充值拉黑----order_sn:"+payOrder.orderNo+"---支付支付宝id:"+notifyInfo.buyer_id+"---绑定支付宝id:"+longInfo.alipayUid);
                    }
                }catch (Exception e){
                    log.error("支付返回处理错误-------用户充值支付宝账号和绑定账号不一致，冻结用户-------", notifyInfo, e);
                }
            }else {
                //次数-1
                if (payOrder.getBusinessType() == 1) {
                    String key = UserKey.rechargeCreateKey(payOrder.getDayKey(), payOrder.getBusyId());
                    String zfbMoneyAllKey = UserKey.rechargeCreateZFBMoneyAllKey(payOrder.getDayKey(), payOrder.getBusyId());
                    String moneyAllKey = UserKey.rechargeCreateMoneyAllKey(payOrder.getDayKey(), payOrder.getBusyId());
                    Redis.key.increment(key, -1);
                    Redis.str.incr(zfbMoneyAllKey, -payOrder.getAmount());
                    Redis.str.incr(moneyAllKey, -payOrder.getAmount());
                }
            }
            return msgInfo.msg;
        } catch (AlipayApiException e) {
            log.error("支付返回处理错误--------------", notifyInfo, e);
            return "fail";
        }
    }

    @RequestMapping("/goods/notify/zfb")
    public String goodsNotifyZfb(AliNotifyAppInfo notifyInfo) {
        if(StringHandler.isEmpty(notifyInfo.out_trade_no)){
            log.error("支付返回订单编号为空: {}", notifyInfo, new RuntimeException());
            return "fail";
        }

        try {
            MsgInfo msgInfo = null;
            String alipayPublicCertPath = "";
            AliPayHandler aliPayHandler = null;
            if (Logger.isOnline()) {
                YsAlipayConfig ysAlipayConfig = ysAlipayConfigManager.ysAlipayConfig(notifyInfo.app_id);
                aliPayHandler = new AliPayHandler(ysAlipayConfig);
                alipayPublicCertPath = ysAlipayConfig.aliCpkCrt;
            } else {
                aliPayHandler = new AliPayHandler("test");
                alipayPublicCertPath = "D:\\\\alipayCertPublicKey_RSA2.crt";
            }
            msgInfo = aliPayHandler.appNotify(notifyInfo, alipayPublicCertPath);

            log.info("notifyZfb--------------------"+Json.toJson(msgInfo));
            if(msgInfo.isSuccess){
                // 修改支付状态
                Order order = orderService.goodsOrderSnInfo(notifyInfo.out_trade_no,-1);
                if(order.getStatus()!=-1){
                    return "success";
                }
                orderService.orderPayStatus(notifyInfo.out_trade_no,1,DateHandler.getLongFormatDate(),"",notifyInfo.trade_no);
            }else {
                orderService.orderPayStatus(StringHandler.getString(notifyInfo.out_trade_no),10,DateUtil.getDatetimeLong(),"",notifyInfo.trade_no);
            }
            return msgInfo.msg;
        } catch (AlipayApiException e) {
            log.error("支付返回处理错误--------------", notifyInfo, e);
            return "fail";
        }
    }
    @RequestMapping("result")
    public String callBack(){
        return "支付成功";
    }

    /**
     * 退款
     * @param orderId
     * @return
     */
    @RequestMapping("refund")
    public String refund(HttpServletRequest request,String orderId){
        String ip2 = RequestHandler.getIP(request);
        if(!ip2.equals(Config.pp.get("ys.recharge.refund.ip"))){
            SystemError.wrapBs("400","此ip不在退款白名单中");
        }
        Map<String,Object> payOrder = orderService.goodsOrderInfo(StringHandler.getLong(orderId),11);
        if(StringHandler.isEmpty(payOrder)){
            SystemError.wrapBs("400","该订单不存在");
        }
        int status = StringHandler.getInt(payOrder.get("status"));
        if(status==11){
            String order_amount = StringHandler.getString(payOrder.get("order_amount"));
            int source = StringHandler.getInt(payOrder.get("source"));
            if(source==2) {
                order_amount = StringHandler.fenToYuan(payOrder.get("order_amount")+"");
            }
            if(StringHandler.getInt(payOrder.get("payChannel"))==2) {
                String requestNo = BaseParam.getOrderSN();
                Map<String, Object> requestMap = new HashMap<>();
                requestMap.put("requestNo", requestNo);
                requestMap.put("origRequestNo", payOrder.get("order_sn"));//原交易订单业务请求号
                requestMap.put("origTradeSn", StringHandler.getString(payOrder.get("tradeSn")));//原交易订单交易流水号
                requestMap.put("refundSource", "01");//退款资金来源，不传值则默认02 01-一般消费类账户 （原订单收款方） 02-待结算账户（原订单收款方当天收单金额） 03-发起方一般消费类账户（发起方）
                requestMap.put("amount", order_amount);
                if (StringHandler.getInt(Config.pp.get("ys.pay.test.open"), 0) == 1) {
                    String testUser = StringHandler.getString(Config.pp.get("ys.pay.test.user"), "");
                    if (StringHandler.isNotEmpty(testUser)) {
                        List<String> testUserList = Arrays.asList(testUser.split(","));
                        if (testUserList.contains(StringHandler.getString(payOrder.get("uid")))) {
                            requestMap.put("amount", "0.01");
                        }
                    }
                }
                requestMap.put("reason", "用户申请退款");    //退款原因
                requestMap.put("isDivision", "N");    //原交易订单是否分账Y-是、N-否
                requestMap.put("notifyUrl", "https://interface.ys168.vip/ys/callBack/refund/notify");    //	String	O	退款结果异步通知地址，为空则不通知
                RequestData requestData = new RequestData(requestMap);
                YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_REFUND);
                List<String> l = new ArrayList<>();
                DynamicDataSourceContextHolder.setDataSourceKey("ysGoods");
                transactionTemplate.execute(e -> {
                    int refund = orderService.refundStatusUpdate(orderId);
                    if (refund <= 0) {
                        SystemError.wrapBs("400", "该订单已退款");
                    }
                    Map<String, Object> map = yinShengClient.requestApi(requestData, "退款");
                    if (StringHandler.isEmpty(map)) {
                        SystemError.wrapBs("500", "退款失败");
                    }
                    l.add(StringHandler.getString(map.get("refundSn")));
                    return 1;
                });
                DynamicDataSourceContextHolder.clearDataSourceKey();
                if (l.size() > 0) {
                    //修改退款订单号
                    orderService.goodsOrderRefundUpdate(orderId, l.get(0));
                }

            }
            if(StringHandler.getInt(payOrder.get("payChannel"))==1){
                int refund = orderService.refundStatusUpdate(orderId);
                if (refund <= 0) {
                    SystemError.wrapBs("400", "该订单已退款");
                }
                int i = orderService.goodsOrderRefund(StringHandler.getLong(orderId),BaseParam.busNo("TK"),DateHandler.getLongFormatDate());
                if(i<=0){
                    log.error("refundNotify--------退单失败，订单ID["+orderId+"],请联系技术处理");
                    SystemError.wrapBs("400", "退单失败,请联系技术处理");
                }else{
                    //订单收款人账号退款
                    PayManager.accountModify(StringHandler.getLong(payOrder.get("uid")), PayEnum.AccountFlowType.PAY_ORDER_MONEY_REFUND, StringHandler.yuanToFen(order_amount), "订单支付退款",2);
                }
            }
            if(StringHandler.getInt(payOrder.get("payChannel"))==3){
                int refund = orderService.refundStatusUpdate(orderId);
                if (refund <= 0) {
                    SystemError.wrapBs("400", "该订单已退款");
                }
//                AliPayHandler aliPayHandler = new AliPayHandler(Config.pp);
//                List<String> obj = JSONObject.parseArray(Config.pp.get("ys.apipay.appid"),String.class);
//                JSONObject bizContent = new JSONObject();
//                bizContent.put("out_trade_no",payOrder.get("order_sn"));
//                bizContent.put("refund_amount",payOrder.get("order_amount"));
//                bizContent.put("refund_reason",payOrder.get("goods_name")+"--退款");
//                try {
//                    MsgInfo  msgInfo = aliPayHandler.refund(obj.get(0),bizContent);
//                    if(msgInfo.isSuccess){
//                        int i = orderService.goodsOrderRefund(StringHandler.getLong(orderId),msgInfo.thirdOrder,DateHandler.getLongFormatDate());
//                        if(i<=0){
//                            log.error("refundNotify--------退单失败，订单ID["+orderId+"],请联系技术处理");
//                            SystemError.wrapBs("400", "退单失败,请联系技术处理");
//                        }
//                    }else{
//                        SystemError.wrapBs("400", "退单失败,请联系技术处理");
//                    }
//                } catch (AlipayApiException e) {
//                    SystemError.wrapBs("400", "退单失败,请联系技术处理");
//                }
                int i = orderService.goodsOrderRefund(StringHandler.getLong(orderId),BaseParam.busNo("TK"),DateHandler.getLongFormatDate());
                if(i<=0){
                    log.error("refundNotify--------退单失败，订单ID["+orderId+"],请联系技术处理");
                    SystemError.wrapBs("400", "退单失败,请联系技术处理");
                }else{

                    //订单收款人账号退款
                    PayManager.accountModifyZfb(StringHandler.getLong(payOrder.get("uid")), PayEnum.AccountFlowType.PAY_ORDER_MONEY_REFUND, StringHandler.yuanToFen(order_amount), "订单支付退款");
                }
            }
        }
        return ResponseHandler.success();
    }

    @RequestMapping("pays")
    public String pays(String orderNo, @RequestParam(defaultValue = "0")int type){
        JSONObject jsonObject = MobaoPay.tradeStatusQuery(orderNo);
        if(type==99){
            String status = jsonObject.getString("orderStatus");
            //支付失败处理
            if(status.equals("02") || status.equals("08") || status.equals("-1")){
                PayOrder payOrder = payService.payOrderBySerialNumber(orderNo);
                if(payOrder.getBusinessType()==1){
                    String key = UserKey.rechargeCreateKey(payOrder.getDayKey(), payOrder.getBusyId());
                    String zfbMoneyAllKey = UserKey.rechargeCreateZFBMoneyAllKey(payOrder.getDayKey(), payOrder.getBusyId());
                    String moneyAllKey = UserKey.rechargeCreateMoneyAllKey(payOrder.getDayKey(), payOrder.getBusyId());
                    Redis.key.increment(key, -1);
                    Redis.str.incr(zfbMoneyAllKey, -payOrder.getAmount());
                    Redis.str.incr(moneyAllKey, -payOrder.getAmount());
                }
                payOrder.setPayStatus(PayEnum.PayStatus.FAIL.getCode());
                payService.payOrderStatusChange(payOrder);
                orderService.orderTimeOut(StringHandler.getString(payOrder.getOrderId()));
            }
        }
        return ResponseHandler.success(jsonObject);
    }
}
